<!-- 首页位置选择功能测试页面 -->
<template>
  <view class="min-h-screen bg-gray-50 p-6">
    <!-- 页面标题 -->
    <view class="mb-8">
      <text class="text-[36rpx] font-bold text-gray-900 text-center">首页位置选择功能测试</text>
    </view>

    <!-- 功能说明 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">功能说明</view>
      <view class="space-y-3 text-[24rpx] text-gray-700">
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            1
          </view>
          <text class="flex-1">点击首页顶部的位置信息，弹出区域选择器</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            2
          </view>
          <text class="flex-1">选择省份后自动加载对应城市列表</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            3
          </view>
          <text class="flex-1">确认选择后更新locationObj.address_component</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            4
          </view>
          <text class="flex-1">首页位置显示会实时更新</text>
        </view>
      </view>
    </view>

    <!-- 模拟首页位置区域 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">模拟首页位置区域</view>
      
      <view 
        class="location flex items-center text-[28rpx] font-medium p-4 bg-gray-50 rounded-xl cursor-pointer transition-all duration-200 active:bg-gray-100"
        @click="handleLocation"
      >
        <IconFont name="location" size="14" class="mr-[10rpx] text-blue-600"></IconFont>
        <text class="text-gray-700">
          {{ currentLocation.province || '未授权定位' }} · {{ currentLocation.city || '未授权定位' }}
        </text>
        <IconFont name="arrow-down" size="12" class="ml-auto text-gray-400"></IconFont>
      </view>
      
      <view class="mt-4 p-3 bg-blue-50 rounded-lg">
        <text class="text-[24rpx] text-blue-600 font-medium">点击上方位置区域进行测试</text>
      </view>
    </view>

    <!-- 当前locationObj状态 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">当前locationObj状态</view>
      <view class="space-y-3 text-[24rpx] text-gray-700">
        <view class="flex justify-between">
          <text>省份：</text>
          <text class="font-medium text-blue-600">{{ currentLocation.province || '未设置' }}</text>
        </view>
        <view class="flex justify-between">
          <text>城市：</text>
          <text class="font-medium text-blue-600">{{ currentLocation.city || '未设置' }}</text>
        </view>
        <view class="flex justify-between">
          <text>完整地址：</text>
          <text class="font-medium text-green-600">{{ fullAddress }}</text>
        </view>
      </view>
    </view>

    <!-- 操作历史 -->
    <view v-if="operationHistory.length > 0" class="bg-white rounded-2xl p-6 shadow-sm">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">操作历史</view>
      <view class="space-y-3">
        <view 
          v-for="(record, index) in operationHistory" 
          :key="index"
          class="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
        >
          <view class="flex items-center">
            <IconFont name="check-circle" class="text-green-600 mr-2" size="24rpx" />
            <text class="text-[24rpx] text-gray-800">{{ record.operation }}</text>
          </view>
          <text class="text-[22rpx] text-gray-500">{{ record.timestamp }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'
import Taro from '@tarojs/taro'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/user'

// 用户store
const userStore = useUserStore()
const { locationObj } = storeToRefs(userStore)

// 响应式数据
const showRegionPicker = ref(false)
const provinceList = ref<any[]>([])
const cityList = ref<any[]>([])
const selectedProvince = ref<any>(null)
const selectedCity = ref<any>(null)
const loading = ref(false)
const operationHistory = ref<Array<{
  operation: string
  timestamp: string
}>>([])

// 当前位置信息
const currentLocation = computed(() => {
  return {
    province: locationObj.value?.address_component?.province,
    city: locationObj.value?.address_component?.city
  }
})

// 完整地址
const fullAddress = computed(() => {
  const parts = []
  if (currentLocation.value.province) parts.push(currentLocation.value.province)
  if (currentLocation.value.city) parts.push(currentLocation.value.city)
  return parts.length > 0 ? parts.join(' ') : '未设置位置'
})

/**
 * 添加操作记录
 */
const addOperationRecord = (operation: string) => {
  operationHistory.value.unshift({
    operation,
    timestamp: new Date().toLocaleTimeString()
  })
  
  // 只保留最近10条记录
  if (operationHistory.value.length > 10) {
    operationHistory.value = operationHistory.value.slice(0, 10)
  }
}

/**
 * 处理位置点击
 */
const handleLocation = () => {
  showRegionPicker.value = true
  loadProvinceData()
  addOperationRecord('打开区域选择器')
}

/**
 * 加载省份数据
 */
const loadProvinceData = async () => {
  if (provinceList.value.length > 0) return
  
  try {
    loading.value = true
    const response = await fetch(`https://apis.map.qq.com/ws/district/v1/list?key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&parent=0`)
    
    if (!response.ok) {
      throw new Error('网络请求失败')
    }
    
    const data = await response.json()
    
    if (data.status !== 0) {
      throw new Error(data.message || '获取数据失败')
    }
    
    provinceList.value = data.result.map((item: any) => ({
      code: item.id,
      name: item.fullname,
      level: item.level
    }))
    
    addOperationRecord(`加载省份数据成功，共${provinceList.value.length}个省份`)
  } catch (error) {
    console.error('获取省份数据失败:', error)
    Taro.showToast({
      title: '获取省份数据失败',
      icon: 'none'
    })
    addOperationRecord('加载省份数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 选择省份
 */
const selectProvince = async (province: any) => {
  selectedProvince.value = province
  selectedCity.value = null
  cityList.value = []
  
  try {
    loading.value = true
    const response = await fetch(`https://datavmap-public.oss-cn-hangzhou.aliyuncs.com/areas/csv/${province.code}_city.json`)
    
    if (!response.ok) {
      throw new Error('网络请求失败')
    }
    
    const data = await response.json()
    
    if (!data.rows || !Array.isArray(data.rows)) {
      throw new Error('数据格式错误')
    }
    
    cityList.value = data.rows.map((item: any) => ({
      code: item.adcode,
      name: item.name,
      level: 2,
      parentCode: province.code
    }))
    
    addOperationRecord(`选择省份：${province.name}，加载${cityList.value.length}个城市`)
  } catch (error) {
    console.error('获取城市数据失败:', error)
    Taro.showToast({
      title: '获取城市数据失败',
      icon: 'none'
    })
    addOperationRecord(`选择省份：${province.name}，加载城市失败`)
  } finally {
    loading.value = false
  }
}

/**
 * 选择城市
 */
const selectCity = (city: any) => {
  selectedCity.value = city
  addOperationRecord(`选择城市：${city.name}`)
}

/**
 * 确认区域选择
 */
const confirmRegionSelection = () => {
  if (!selectedProvince.value) {
    Taro.showToast({
      title: '请选择省份',
      icon: 'none'
    })
    return
  }
  
  if (!selectedCity.value) {
    Taro.showToast({
      title: '请选择城市',
      icon: 'none'
    })
    return
  }
  
  // 更新locationObj
  locationObj.value = {
    ...locationObj.value,
    address_component: {
      ...locationObj.value.address_component,
      province: selectedProvince.value.name,
      city: selectedCity.value.name
    }
  }
  
  // 关闭弹窗
  showRegionPicker.value = false
  
  const operationText = `确认选择：${selectedProvince.value.name} ${selectedCity.value.name}`
  addOperationRecord(operationText)
  
  Taro.showToast({
    title: `已选择：${selectedProvince.value.name} ${selectedCity.value.name}`,
    icon: 'success'
  })
}

// 模拟区域选择弹窗（简化版）
// 注意：这里只是测试逻辑，实际使用时需要完整的弹窗组件
</script>
